﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Step4.Unit9.Models;
using System.Security.Claims;
using System.Web;

namespace Step4.Unit9.Controllers
{
    public class AccountController : Controller
    {
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly UserManager<IdentityUser> _userManager;

        public AccountController(SignInManager<IdentityUser> signInManager)
        {
             _signInManager =signInManager;
            _userManager = _signInManager.UserManager;
        }

        /// <summary>
        /// 登录视图
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous] // 允许匿名访问
        public IActionResult Login(string? redirectUrl =null)
        {
            LoginViewModel viewModel = new LoginViewModel { RedirectUrl = redirectUrl };
            return View(viewModel); // 通过视图模型，把redirectUrl传给前端
        }

        /// <summary>
        /// 登录提交方法
        /// </summary>
        [HttpPost]
        [AllowAnonymous]  // 允许任何人访问  (默认就是允许任何人访问的)
        public async Task<IActionResult> SubmitLogin(LoginViewModel model)
        {
            if (ModelState.IsValid) // 判断模型是否校验成功
            {
                // 获取用户
                var user = await _signInManager.UserManager.FindByNameAsync(model.UserName);
                if (user != null)
                {
                    //await _signInManager.SignInAsync(user,
                    //   false, // 浏览器不存储用户名密码，下次打开登录页面要重新输入
                    //   model.Pwd);
                    var result = await _signInManager.PasswordSignInAsync(user,      // 用户对象
                                                              model.Pwd, // 密码
                                                              false,     // 浏览器是否存储用户名密码
                                                              false);    // 如果登录失败是否锁定账户
                    if (result.Succeeded)
                    {
                        // 登录成功后跳转到目标地址
                        if (!string.IsNullOrEmpty(model.RedirectUrl))
                        {                   // 对CustomerAuthorizationAttribute 传递给Login视图的redirectUrl进行"Url解码" 
                            return Redirect(HttpUtility.UrlDecode(model.RedirectUrl)); 
                        }
                        return RedirectToAction("Index", "Home");
                    }
                    ModelState.AddModelError("", "用户名或密码不正确");
                }
                else {
                    ModelState.AddModelError("", "您输入的用户名不存在");
                }
            }
            return View("Login", model);  // 如果校验不成功，返回登录视图，用户填写信息的模型回填
        }

        /// <summary>
        /// 注册视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Register()
        {

            return View();
        }

        [Authorize]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction("Login");
        }
    }
}
